<?php

namespace app\common\helper;

use GuzzleHttp\Client;

class BaiDuAi
{
    protected $api_key;
    protected $secret;
    protected $data;
    public function __construct()
    {
        $this->api_key = 'EIIZW9N1eOEXsi8nBlOSXumZ';
        $this->secret = 'PaZQN7eyqVaOZdhk8gSNRoovinzKsNC4';
    }

    public function send()
    {
        $url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2imgv2?access_token=" . $this->getAccessToken();
        $client = new Client();
        $result = $client->post($url,[
            'json' => $this->data
        ]);
        return json_decode($result->getBody()->getContents(),true);
    }

    public function search()
    {
        $url = "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImgv2?access_token=" . $this->getAccessToken();
        $client = new Client();
        $result = $client->post($url,[
            'json' => $this->data
        ]);
        return json_decode($result->getBody()->getContents(),true);
    }

    public function withData($data)
    {
        $this->data = $data;
        return $this;
    }
    protected function getAccessToken()
    {
        $token = cache('baidu_token');
        if (!$token) {
            $url = 'https://aip.baidubce.com/oauth/2.0/token';
            $client = new Client();
            $param = [
                "grant_type" => "client_credentials",
                "client_id" => $this->api_key,
                "client_secret" => $this->secret
            ];
            $url .= "?" . http_build_query($param);
            $result = $client->post($url);
            $result = json_decode($result->getBody()->getContents(),true);
            if (isset($result['access_token'])) {
                $token = $result['access_token'];
                cache('baidu_token',$token,$result['expires_in']);
            }
        }
        return $token;
    }
}